#include "file_util.h"

#include <string.h>

void gbk_to_utf8(const char* src, char* dst, size_t len)
{
    // �� Windows �����ÿ���̨����Ĵ���ҳΪ UTF-8
#ifdef _WIN32
    SetConsoleOutputCP(CP_UTF8);
#endif

    // �� Linux �����ñ��ػ�����Ϊ UTF-8
#ifdef __linux__
    setlocale(LC_ALL, "en_US.utf8");
#endif

#ifdef _WIN32
    int utf8_length = MultiByteToWideChar(CP_ACP, 0, src, -1, NULL, 0);
    if (utf8_length == 0) {
        fprintf(stderr, "GBK to UTF-8 conversion failed\n");
        return;
    }

    wchar_t* wide_string = (wchar_t*)malloc(utf8_length * sizeof(wchar_t));
    MultiByteToWideChar(CP_ACP, 0, src, -1, wide_string, utf8_length);

    int utf8_bytes = WideCharToMultiByte(CP_UTF8, 0, wide_string, -1, dst, len, NULL, NULL);
    if (utf8_bytes == 0) {
        fprintf(stderr, "GBK to UTF-8 conversion failed\n");
    }

    free(wide_string);
#endif

#ifdef __linux__
    iconv_t cd = iconv_open("UTF-8", "GBK");
    if (cd == (iconv_t)-1) {
        fprintf(stderr, "GBK to UTF-8 conversion failed\n");
        return;
    }

    size_t src_length = strlen(src);
    size_t result = iconv(cd, (char**)&src, &src_length, &dst, &len);
    if (result == (size_t)-1) {
        fprintf(stderr, "GBK to UTF-8 conversion failed\n");
    }

    iconv_close(cd);
#endif
}